import os
from pathlib import Path
from concurrent_log_handler import ConcurrentRotatingFileHandler
import logging.config


# BASE_DIR = Path(__file__).resolve().parent.parent
# LOG_BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
LOG_BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# log_format = '%(asctime)s | Request ID: %(request_id)s | %(module)s | %(funcName)s | %(message)s '

BASE_LOG_DIR = os.path.join(LOG_BASE_DIR, "log")
# os.makedirs(BASE_LOG_DIR, mode=0o755, exist_ok=True)
os.makedirs(BASE_LOG_DIR, exist_ok=True)

# logging.basicConfig(format='%(asctime)s-%(filename)s-[line:%(lineno)d]-%(levelname)s: %(message)s',
#                     level=logging.DEBUG)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            # 'format': '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d:%(funcName)s] %(message)s'
            # 'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
            'format':'%(asctime)s-%(filename)s-[line:%(lineno)d]-%(levelname)s: %(message)s'
        },
        'simple':{
            'format':'[%(levelname)s][%(asctime)s] %(message)s'
        }
    },
    'filters': {
        'require_debug_true': {
            # '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'info_file': {
            'level': 'INFO',
            # 'class': 'logging.handlers.RotatingFileHandler',
            'class': 'concurrent_log_handler.ConcurrentRotatingFileHandler',   #多线程日志
            'filename': os.path.join(BASE_LOG_DIR, "log.log"), 
            # 'maxBytes': 1024 * 1024 * 50 * 200,  # 日志大小 10G
            'maxBytes': 1024 * 1024 * 50 * 2,  # 日志大小 100M
            'backupCount': 180,            #保留180天
            'formatter': 'standard',
            'encoding': 'utf-8',
        },
        'error_file': {
            'level': 'ERROR', # 处理来自 Django 请求模块的 ERROR 级别日志
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(BASE_LOG_DIR, 'error.log'),
            'maxBytes': 1024 * 1024 * 50,  # 日志大小 50M
            'backupCount': 180,        #保留180天
            'formatter': 'standard',
            'encoding': 'utf-8',
        },
    },
    'loggers': {
        '': {
            # 部署到生产环境之后可以把'console'移除
            'handlers': ['console', 'info_file', 'error_file'],
            'level': 'DEBUG',
        },
    },
}

logging.config.dictConfig(LOGGING)
logger_log = logging.getLogger(__name__)